package i5.modelman.chase;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.io.OutputStream;

import org.apache.log4j.Logger;

/**
 * Locates a resource if available as file otherwise in Jar. This is used to
 * unpack prolog files (or other resources) from a distribution.
 * 
 * @author David Kensche
 * @author Xiang Li
 */
public class ResourceLocator {
	private static Logger logger = Logger.getLogger(ResourceLocator.class);

	/**
	 * 
	 * @param resource
	 *            the resource name
	 * @return an input stream for reading the resource, null if unavailable
	 */
	public static InputStream openResourceAsStream(String resource) {
		return ResourceLocator.class.getClassLoader().getResourceAsStream(
				resource);
	}

	public static File getFileByName(Class<?> context, String name){
		File file = new File(context.getResource(name).getPath());
		return file;
	}
	
	public static String locateByTmpFile(String name) throws IOException,
			ResourceNotFoundException {
		String canonicalPath = null;
		File file = new File(name);
		if (file.exists()) {
			logger.debug("the file '" + file.getCanonicalPath() + "' exists");
		} else {
			InputStream in = ResourceLocator.class.getClassLoader()
					.getResourceAsStream(name);
			if (in == null) {
				throw new ResourceNotFoundException(
						"The file '"
								+ file
								+ "' could not be found in the working directory nor in the jar files.");
			}
			String filePath = name;// create same-name file under current folder
			logger.debug("tmp-file: " + filePath);
			file = File.createTempFile(filePath, null);

			// Transfer bytes 
			transferData(file, in);
			in.close();

			logger.debug("tmp file created at " + file.getCanonicalPath());

			file.deleteOnExit();
		}
		return file.getCanonicalPath();
	}

	private static void transferData(File targetFile, InputStream in)
			throws FileNotFoundException, IOException {
		OutputStream out = new FileOutputStream(targetFile);
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		out.close();
	}

}
